package com.share.netdisk.share.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.netdisk.share.dao.ShareDao;
import com.share.netdisk.share.model.Share;
import com.share.netdisk.share.model.ShareDTO;
import com.share.netdisk.share.service.ShareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ShareServiceImpl extends ServiceImpl<ShareDao, Share> implements ShareService {

	private static final int MIN_LENGTH = 4;
	private static final int MAX_LENGTH = 6;
	private static final String CHARACTERS = "0123456789"; // 只包含数字

	@Autowired
	private ShareDao shareDao;

	public String createShareLink(Integer userId, Integer fileId, String expireTime) {

		//验证参数有效性
		if (fileId == null || userId == null || expireTime == null || expireTime.isEmpty()) {
			return "参数无效";
		}

		int days = Integer.parseInt(expireTime);
		if (days <= 0) {
			return "日期不合法，请输入正确的日期";
		}


		// 生成唯一的分享码
		String uniqueCode;
		do {
			uniqueCode = generateRandomCode();
		} while (shareDao.existsByFileCode(uniqueCode));

		//创建新的分享记录
		Share share = new Share();
		//获取到文件id、用户id
		share.setFileId(fileId);
		share.setUserId(userId);
		share.setFileCode(uniqueCode);
		share.setExpireTime(expireTime);//设置过期时间

		share.setCreateTime(new Date());//设置创建时间为当前时间

		boolean saveResult = this.save(share);
		if (!saveResult) {
			return "创建失败";
		}
		//构建分享链接
		return "https://xxxxxx/" + share.getUserId() + share.getFileId() + "?code=" + uniqueCode;
	}

	//生成随机验证码的函数
	private String generateRandomCode() {
		Random random = new Random();
		int length = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
		StringBuilder codeBuilder = new StringBuilder(length);

		for (int i = 0; i < length; i++) {
			int index = random.nextInt(CHARACTERS.length());
			codeBuilder.append(CHARACTERS.charAt(index));
		}

		return codeBuilder.toString();
	}

	//修改分享链接
	public String updateExpireTime(Integer shareId, String expireTime) {
		// 验证参数有效性
		if (shareId == null) {
			return "分享ID无效";
		}
		Share share = this.getById(shareId);
		if (share == null) {
			return "分享记录不存在";
		}

		// 验证过期时间参数
		if (expireTime != null && !expireTime.trim().isEmpty()) {
			try {
				int days = Integer.parseInt(expireTime.trim()); // 清理空格
				if (days <= 0) {
					return "过期时间不合法，请输入正整数";
				}
				share.setExpireTime(String.valueOf(days)); // 更新过期时间
			} catch (NumberFormatException e) {
				return "过期时间格式不正确，请输入数字";
			}
		} else {
			return "过期时间不能为空";
		}

		// 更新修改时间为当前时间
		share.setUpdateTime(new Date());

		// 更新数据库记录
		boolean updateResult = this.updateById(share);
		if (!updateResult) {
			return "更新失败";
		}

		return "更新成功";
	}

	//逻辑删除
	public boolean updateStatusById(Integer shareId, Integer status) {
		// 构建查询条件
		LambdaUpdateWrapper<Share> wrapper = new LambdaUpdateWrapper<>();
		wrapper.eq(Share::getShareId, shareId);
		wrapper.set(Share::getStatus, status);

		// 执行更新操作并返回是否成功
		return shareDao.update(null, wrapper) > 0;
	}

	/**
	 * 根据用户ID获取该用户的分享链接列表
	 */
	@Override
	public Map<String, Object> getSharesByUserId(Integer userId, String keyword, int page, int size) {
		// 构建查询条件
		LambdaQueryWrapper<Share> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Share::getUserId, userId)
				.eq(Share::getStatus, "1"); // 状态为1的有效分享链接

		if (keyword != null && !keyword.trim().isEmpty()) {
			queryWrapper.and(wrapper -> wrapper.like(Share::getFileCode, keyword));
		}

		// 使用分页查询
		Page<Share> pageRequest = new Page<>(page, size);
		Page<Share> sharePage = shareDao.selectPage(pageRequest, queryWrapper);

		// 构建分享详情列表
		List<ShareDTO> shareDetails = sharePage.getRecords().stream()
				.map(share -> {
					ShareDTO dto = new ShareDTO();
					dto.setShareId(share.getShareId());
					dto.setShareLink(buildShareLink(share.getUserId(), share.getFileId(), share.getFileCode()));
					dto.setCreateTime(share.getCreateTime());
					dto.setUpdateTime(share.getUpdateTime());
					dto.setExpireTime(share.getExpireTime());
					return dto;
				})
				.collect(Collectors.toList());

		// 返回分页数据和元信息
		Map<String, Object> result = new HashMap<>();
		result.put("records", shareDetails);         // 当前页数据
		result.put("total", sharePage.getTotal());   // 总条目数
		result.put("pageNum", sharePage.getCurrent());// 当前页码
		result.put("pageSize", sharePage.getSize()); // 每页条数

		return result;
	}



//	// 构建分享链接的方法
//	private String buildShareLink(Integer userId, Integer fileId, String fileCode) {
//		// 假设的基础URL，你需要替换为你实际的域名或路径
//		String baseUrl = "https://xxxxxx";
//		return String.format("%s/%d?code=%s", baseUrl, userId, fileId, fileCode);
//	}

	/**
	 * 构建单个分享链接
	 */
	private String buildShareLink(Integer userId, Integer fileId, String fileCode) {
		// 这里替换为你的域名或API端点
		return "https://xxxxxx" + userId + fileId + "?code=" + fileCode;
	}
}
